<template>
  <div id="log_div" style="width: 100%;min-height: 800px;border: 1px solid #ccd1d3;background-color: #f5f5f5"></div>
</template>

<script>
  import { getUUID } from '@/utils/util'

  export default {
    name: "LogstashPipelineLog",
    data () {
      return {
        socket: null,
        socketPath: "ws://127.0.0.1:8099/llog/",
        logDiv: null,
        intervalWebsocketId: null
      }
    },
    props: {
      pipelineId: String
    },
    watch: {
      pipelineId: function (n, o) {
        if(n && this.socket == null){
          this.connWebSocket(n)
        }else if(!n){
          this.clearWebsocket()
        }
      }
    },
    methods: {
      sendWebsocket() {
        // 计时器正在进行中，退出函数
        if (this.intervalWebsocketId != null) {
          return;
        }
        // 计时器为空，操作
        this.intervalWebsocketId = setInterval(() => {
          this.socket.send("1")
        }, 5000);
      },
      clearWebsocket() {
        clearInterval(this.intervalWebsocketId)
        this.intervalWebsocketId = null
        if(this.socket){
          this.socket.close()
        }
        this.socket = null
        if(this.logDiv){
          this.logDiv.innerHTML = ''
        }
      },
      // 停止定时器
      clear() {
        clearInterval(this.intervalId); //清除计时器
        this.intervalId = null; //设置为null
      },
      showLogs(pipelineId) {
        this.showLogFlag = true
        this.connWebSocket(pipelineId)
      },
      hideLogs() {
        this.showLogFlag = false
        this.clearWebsocket()
      },
      connWebSocket(pipelineId) {
        this.socket = new WebSocket("ws://127.0.0.1:8099/llog/" + this.pipelineId + "-" + getUUID())
        this.socket.onopen = this.openWebsocket
        this.socket.onerror = function () {
          console.log("连接错误")
        }
        this.socket.onclose = this.clearWebsocket
        this.socket.onmessage = this.showLogContent
      },
      openWebsocket() {
        this.sendWebsocket()
        this.logDiv = document.getElementById("log_div");
        this.logDiv.innerHTML = ''
      },
      showLogContent(msg) {
        let p = document.createElement("p")
        p.appendChild(document.createTextNode(msg.data))
        this.logDiv.appendChild(p)
      }
    }
  }
</script>

<style scoped>

</style>